package com.xingfly.service;

import com.xingfly.model.Permission;
import com.xingfly.model.Role;
import com.xingfly.model.User;
import com.xingfly.repository.UserRepository;
import com.xingfly.util.CaptchaUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 账户服务
 * Created by SuperS on 2016/11/29.
 */
@Service
public class AccountService {
    public static final String EMAIL_USER_ACTIVATE_KEY_NAME = "email:user:activate:";

    //用户状态
    public static final int STATUS_USER_NORMAL = 0;                //正常
    public static final int STATUS_USER_INACTIVE = 1;            //待激活
    public static final int STATUS_USER_LOCK = 2;                //锁定
    public static final int STATUS_USER_CANCELLED = 3;            //注销

    @Autowired
    private UserRepository userRepository;
    @Autowired
    private MailService mailService;
    @Autowired
    private FollowService followService;
    @Autowired
    private PostService postService;
    @Autowired
    private CaptchaUtil captcha;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private BCryptPasswordEncoder encoder;

    public User find(Long id) {
        return userRepository.findOne(id);
    }

    public void delete(Long id) {
        userRepository.delete(id);
    }

    public void delete(User user) {
        userRepository.delete(user);
    }

    /**
     * 分页获取用户列表
     */
    public Page<User> getUsers(Pageable pageable) {
        return userRepository.findAll(pageable);
    }


    /**
     * 创建用户
     */
    public User save(User user) {
        String hash = encoder.encode(user.getPassword());
        user.setPassword(hash);
        return userRepository.save(user);
    }

    /**
     * 更新用户
     */
    public User update(User user) {
        return userRepository.save(user);
    }

    /**
     * 根据用户名查找用户
     */
    public User find(String username) {
        return userRepository.findUserByUsername(username);
    }

    /**
     * 根据用户名查找角色
     */
    public List<Role> findRoles(String username) {
        return userRepository.findUserByUsername(username).getRoles();
    }

    /**
     * 根据用户名查找权限
     */
    public List<Permission> findPermissions(String username) {
        List<Permission> permissions = new ArrayList<>();
        List<Role> roles = findRoles(username);
        for (Role role : roles) {
            permissions.addAll(role.getPermissions());
        }
        return permissions;
    }

    /**
     * 邮箱验证
     */
    private boolean validateEmail(String email) {
        boolean result = true;
        try {
            InternetAddress emailAddress = new InternetAddress(email);
            emailAddress.validate();
        } catch (AddressException e) {
            result = false;
        }
        return result;
    }

    /**
     * 根据邮箱查找用户
     */
    public User findByEmail(String email) {
        return userRepository.findUserByMail(email);
    }

    /**
     * 根据手机号查找用户
     * */
    public User findByPhone(String phone){
        return userRepository.findUserByPhone(phone);
    }
    /**
     * 生成邮箱验证码
     *
     * @param email key为email
     */
    public String creteEmailCaptcha(String email) {
        String key = captcha.randomCaptcha();
        redisTemplate.opsForValue().set(EMAIL_USER_ACTIVATE_KEY_NAME + email, key);
        redisTemplate.expire(EMAIL_USER_ACTIVATE_KEY_NAME + email, 12, TimeUnit.HOURS);
        return key;
    }

    /**
     * 获取邮箱验证码
     *
     * @param email key为email
     */
    public String getEmailCaptcha(String email) {
        return redisTemplate.opsForValue().get(EMAIL_USER_ACTIVATE_KEY_NAME + email);
    }


    /**
     * 发送用户激活码
     */
    public boolean sendUserActivateCode(String email, String activateCode) {
        try {
            mailService.sendAccountActivationEmail(email, activateCode);
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    /**
     * 关闭用户
     */
    public void closeUser(User user) {
        user.setEnable(false);
        userRepository.save(user);
    }

    //添加头像

    //修改头像

    //根据List<Long> ids获取集合中所有用户对象


    //用户注册

    //更新用户激活码

    //获取用户状态

    //更新用户信息 昵称 描述 等。


    //检查是否有权重置密码

    //修改密码

    //推荐用户


}
